//
//  LBCityPickerView.m
//  app
//
//  Created by 赵辉 on 16/7/12.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBCityPickerView.h"
#import "LBCityMsgModel.h"
#import "LBCityDataManager.h"
#import "MJExtension.h"
#import "Masonry.h"

#define SCREEN_With [[UIScreen mainScreen] bounds].size.width
#define SCREEN_Height [[UIScreen mainScreen] bounds].size.height

typedef NS_ENUM(NSInteger,LBCityPickerViewComponentType) {
    LBCityPickerViewComponentTypeOne = 0,
    LBCityPickerViewComponentTypeTwo = 1,
    LBCityPickerViewComponentTypeThree = 2
};

static CGFloat const LBCityPickerViewCityPickerTopHeight = 35;

static CGFloat const LBCityPickerViewCityPickerHeight = (216 + LBCityPickerViewCityPickerTopHeight);

static CGFloat const LBCityPickerViewLineHeight = 30;

@interface LBCityPickerView ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) UIView *cityPickerBgView;

@property (strong, nonatomic) UIPickerView  *pickerView;

@property (copy, nonatomic) lbCityPickViewChoseBlock currentChoseBlock;

@property (strong, nonatomic) NSMutableDictionary *selectedCityMsgDic;

@property (strong, nonatomic) LBCityMsgModel *selectedProvinceModel;

@property (strong, nonatomic) LBCityMsgModel *selectedCityModel;

@property (strong, nonatomic) LBCityMsgModel *selectedAreaModel;

@property (nonatomic,strong) LBCityDataManager *chinaModel;

@property (strong, nonatomic) NSMutableArray <LBCityMsgModel *> *allCityArray;

@property (assign, nonatomic) LBCityPickerViewType currentCityType;

@property (assign, nonatomic) NSInteger componentCount;

@end

@implementation LBCityPickerView

+ (instancetype)shareCityPicker
{
    static LBCityPickerView *shareCityPicker = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareCityPicker = [[LBCityPickerView alloc]initWithFrame:[[UIApplication sharedApplication].delegate window].bounds];
        [[[UIApplication sharedApplication].delegate window] addSubview:shareCityPicker];
        [shareCityPicker setHidden:YES];
    });
    
    if (!shareCityPicker.allCityArray.count) {
        //防止初始化时地址获取不到
        [shareCityPicker getCityModel];
    }
    return shareCityPicker;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createAllView];
    }
    return self;
}

- (void)createAllView
{
    //default
    self.componentCount = 3;
    _currentCityType = LBCityPickerViewTypeProvincialCityAreas;
    
    [self addSubview:self.cityPickerBgView];
    
    [self addTarget:self action:@selector(closeCurrentView) forControlEvents:UIControlEventTouchUpInside];
    
    self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    
    [self getCityModel];
}

- (NSMutableArray <LBCityMsgModel *> *)cityMsgArray {
    
    return self.allCityArray;
}

- (void)getCityModel
{
    
    self.allCityArray = [NSMutableArray arrayWithArray:[LBCityDataManager getCityModelArray]];
    //default
    self.selectedProvinceModel = [self.allCityArray firstObject];
    self.selectedCityModel = [self.selectedProvinceModel.eachArea firstObject];
    self.selectedAreaModel = [self.selectedCityModel.eachArea firstObject];
}

- (void)reloadPickViewWithRow:(LBCityPickerViewComponentType)row{
    if (LBCityPickerViewComponentTypeOne == row) {
        [self.pickerView reloadAllComponents];
        for (NSInteger i = 1; i < self.componentCount; i++) {
            [self.pickerView selectRow:0 inComponent:i animated:YES];
        }
    } else if (LBCityPickerViewComponentTypeTwo == row){
        if (3 == self.componentCount) {
            [self.pickerView reloadComponent:2];
            [self.pickerView selectRow:0 inComponent:2 animated:YES];
        }
        
    }
}

#pragma mark - setter

- (void)setCurrentCityType:(LBCityPickerViewType)currentCityType
{
    if (_currentCityType == currentCityType) {
        return;
    }
    _currentCityType = currentCityType;

    switch (_currentCityType) {
        case LBCityPickerViewTypeProvincialCityAreas: {
            self.componentCount = 3;
            break;
        }
        case LBCityPickerViewTypeProvincialCity: {
            self.componentCount = 2;
            break;
        }
    }
    [self.pickerView reloadAllComponents];
}

#pragma mark - getter

- (UIView *)cityPickerBgView
{
    if (!_cityPickerBgView) {
        _cityPickerBgView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_Height, SCREEN_With, LBCityPickerViewCityPickerHeight)];
        _cityPickerBgView.backgroundColor = [UIColor whiteColor];
        
        UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width,LBCityPickerViewCityPickerTopHeight)];
        topView.backgroundColor = [UIColor colorWithRed:243/255.0 green:244/255.0 blue:245/255.0 alpha:1];
        
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [cancelButton setTitleColor:[UIColor colorWithRed:92/255.0 green:167/255.0 blue:240/255.0 alpha:1] forState:UIControlStateNormal];
        cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        UILabel *titleLabel = [[UILabel alloc]init];
        [titleLabel setText:@"选择地区"];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor lightGrayColor];
        
        UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        [confirmButton setTitleColor:[UIColor colorWithRed:92/255.0 green:167/255.0 blue:240/255.0 alpha:1] forState:UIControlStateNormal];
        confirmButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        [_cityPickerBgView addSubview:topView];
        
        [topView addSubview:cancelButton];
        [topView addSubview:titleLabel];
        [topView addSubview:confirmButton];
        
        [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(topView).offset(15);
            make.centerY.mas_equalTo(topView);
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(topView);
            make.centerY.mas_equalTo(topView);
        }];
        
        [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(topView).offset(-15);
            make.centerY.mas_equalTo(topView);
        }];
        
        [cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        
        [confirmButton addTarget:self action:@selector(confirmActon) forControlEvents:UIControlEventTouchUpInside];
        
        [_cityPickerBgView addSubview:self.pickerView];
        
        CGRect newRect = _cityPickerBgView.bounds;
        
        newRect.origin.y = LBCityPickerViewCityPickerTopHeight;
        
        newRect.size.height -= LBCityPickerViewCityPickerTopHeight;
        
        [self.pickerView setFrame:newRect];

    }
    return _cityPickerBgView;
}

- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] init];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
    }
    return _pickerView;
}

- (NSMutableDictionary *)selectedCityMsgDic
{
    if (!_selectedCityMsgDic) {
        _selectedCityMsgDic = [NSMutableDictionary dictionary];
    }
    return _selectedCityMsgDic;
}

#pragma mark -action

- (void)cancelAction
{
    [self closeCurrentView];
}

- (void)confirmActon
{
    [self closeCurrentView];
    if (self.currentChoseBlock) {
        self.currentChoseBlock(self.selectedProvinceModel,self.selectedCityModel,self.selectedAreaModel);
    }
}

+ (void)showCityPickViewByAnimation:(BOOL)animation
                         Complete:(lbCityPickViewChoseBlock)choseBlock;
{
    LBCityPickerView *datePickerView = [self shareCityPicker];
    
    [[[UIApplication sharedApplication].delegate window] bringSubviewToFront:datePickerView];
    
    [datePickerView setHidden:NO];
    
    if (datePickerView.cityPickerBgView.frame.origin.y != SCREEN_Height) {
        CGRect frame = datePickerView.cityPickerBgView.frame;
        frame.origin.y = SCREEN_Height;
        datePickerView.cityPickerBgView.frame = frame;
    }
    datePickerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0];
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        datePickerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        CGRect frame = datePickerView.cityPickerBgView.frame;
        frame.origin.y = SCREEN_Height - LBCityPickerViewCityPickerHeight;
        datePickerView.cityPickerBgView.frame = frame;
    } completion:^(BOOL finished) {
    }];
}

+ (void)showCityPickViewByAnimation:(BOOL)animation
               LBCityPickerViewType:(LBCityPickerViewType)cityType
                           Complete:(lbCityPickViewChoseBlock)choseBlock
{
    LBCityPickerView *datePickerView = [self shareCityPicker];
    
    datePickerView.currentChoseBlock = choseBlock;
    
    [[[UIApplication sharedApplication].delegate window] bringSubviewToFront:datePickerView];
    
    datePickerView.currentCityType = cityType;
    
    [datePickerView setHidden:NO];
    
    if (datePickerView.cityPickerBgView.frame.origin.y != SCREEN_Height) {
        CGRect frame = datePickerView.cityPickerBgView.frame;
        frame.origin.y = SCREEN_Height;
        datePickerView.cityPickerBgView.frame = frame;
    }
    datePickerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0];
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        datePickerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        CGRect frame = datePickerView.cityPickerBgView.frame;
        frame.origin.y = SCREEN_Height - LBCityPickerViewCityPickerHeight ;
        datePickerView.cityPickerBgView.frame = frame;
    } completion:^(BOOL finished) {
    }];
}

- (void)closeCurrentView
{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0];
        CGRect frame = self.cityPickerBgView.frame;
        frame.origin.y = SCREEN_Height;
        self.cityPickerBgView.frame = frame;
    } completion:^(BOOL finished) {
        [self setHidden:YES];
    }];
}

#pragma mark - UIPickerViewDelegate, UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return self.componentCount;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) { // 省份
        return self.allCityArray.count;
    }
    else if (component == 1){ // 城市
        return self.selectedProvinceModel.eachArea.count;
    }
    else{ // 区域
        return self.selectedCityModel.eachArea.count;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return (self.frame.size.width - 20)/self.componentCount;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return LBCityPickerViewLineHeight;
}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (0 == component) {
        LBCityMsgModel *provinceModel;
        if (row < self.allCityArray.count) {
            provinceModel = self.allCityArray[row];
        }
        return provinceModel.areaName;
    } else if (1 == component) {
        LBCityMsgModel *cityModel;
        if (row < self.selectedProvinceModel.eachArea.count) {
            cityModel = self.selectedProvinceModel.eachArea[row];
        }
        return cityModel.areaName;
    } else {
        LBCityMsgModel *areaModel;
        if (row < self.selectedCityModel.eachArea.count) {
            areaModel = self.selectedCityModel.eachArea[row];
        }
        return areaModel.areaName;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    switch (component) {
        case 0:{ // 选择省份
            if (row < self.allCityArray.count) {
                self.selectedProvinceModel = self.allCityArray[row];
                if (0 < self.selectedProvinceModel.eachArea.count) {
                    self.selectedCityModel = self.selectedProvinceModel.eachArea[0];
                    if (0 < self.selectedCityModel.eachArea.count) {
                        self.selectedAreaModel = self.selectedCityModel.eachArea[0];
                    }
                }
                
            }
            [self reloadPickViewWithRow:LBCityPickerViewComponentTypeOne];
            break;
        }
        case 1:{ // 选择城市
            if (row < self.selectedProvinceModel.eachArea.count) {
                self.selectedCityModel = self.selectedProvinceModel.eachArea[row];
                if (0 < self.selectedCityModel.eachArea.count) {
                    self.selectedAreaModel = self.selectedCityModel.eachArea[0];
                }
            }
            [self reloadPickViewWithRow:LBCityPickerViewComponentTypeTwo];
            break;
        }
        case 2: // 选择区域
            if (row < self.selectedCityModel.eachArea.count) {
                self.selectedAreaModel = self.selectedCityModel.eachArea[row];
            }
            break;
        default:
            break;
    }

}

@end
